import re
import requests
from app.common import mongo_client
from settings import openapi_settings, mongo_settings


def http_latest_lottery():
    """根据期数获取"""
    url = openapi_settings.api_phase_history
    headers = {'Referer': openapi_settings.api_refer}
    resp = requests.get(url, headers=headers)
    if resp.status_code != 200:
        raise requests.exceptions.HTTPError('请求依赖接口失败')
    resp_json = resp.json()
    if resp_json['state'] != 0:
        raise requests.exceptions.HTTPError('请求依赖接口返回数据异常')
    return resp_json['result']


def parse_lottery_from_rawdata(rawdata):
    """从原始数据中提取数据"""
    data = {
        '_id': rawdata['code'],
        'date': re.search(r'(\d{4}-\d{2}-\d{2})', rawdata['date']).group(),
        'blue': rawdata['blue'],
        'red': rawdata['red'].split(','),
        'poolmoney': rawdata['poolmoney'],
        'prizegrades': [
            {
                'grade': grade['type'],
                'number': grade['typenum'],
                'bonus': grade['typemoney']
            } for grade in rawdata['prizegrades']
        ]
    }
    return data


def scrapy_latest_lottery():
    """爬取最新的彩票信息"""
    results = http_latest_lottery()
    data = parse_lottery_from_rawdata(results[0])

    query = {'_id': data['_id']}
    mongo_client.execute(
        mongo_client.client[mongo_settings.db_lottery][mongo_settings.col_lottery].update,
        query, {'$set': data},
        upsert=True
    )
